package com.song.service.impl;


import com.song.dao.impl.AdministratorDaoImpl;
import com.song.exception.adminException.AdminRegisterNameException;
import com.song.exception.adminException.AdminRegisterPhoneException;
import com.song.polo.Administrator;
import com.song.service.AdministratorService;
import com.song.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

@Service
public class AdministratorServiceImpl implements AdministratorService {
    @Autowired
    private AdministratorDaoImpl administratorDao;

    /**
     * 用户登录
     *
     * @param administratorName 用户名
     * @param password          用户密码
     * @return true 登录成功
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {Exception.class})
    public Administrator login(String administratorName, String password) {
        return  administratorDao.login(administratorName, password);
    }

    /**
     * 更新登录时间与登录IP地址
     *
     * @param administratorName 用户名
     * @param ipAddress         登录IP地址
     * @param loginTime         登录时间
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void updateLoginTime(String administratorName, String ipAddress, Timestamp loginTime) {
        administratorDao.updateLoginTime(administratorName, ipAddress, loginTime);
    }

    /**
     * 用户的注册
     *
     * @param administrator 用户注册信息
     * @return true 注册成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Integer register(Administrator administrator) {
        Integer register = null;

        try {
            administrator.setRegisterTime(DateUtil.getTimestamp());
           register = administratorDao.register(administrator);

        } catch (AdminRegisterNameException | AdminRegisterPhoneException e) {
            if (e.getMessage().endsWith("key 'administrator.administratorName'")){
               return 0;
            }
            if (e.getMessage().endsWith("key 'administrator.administratorPhone'")){
                return -1;
            }
        }
        return register;
    }

    /**
     * 通过手机号查询用户
     *
     * @param administratorPhone 用户的手机号
     * @return 查询的用户对象
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {Exception.class})
    public Administrator selectByPhone(String administratorPhone, String administratorName) {
        return administratorDao.selectByPhone(administratorPhone, administratorName);
    }
}
